<template>
    <div class="page-container">
        <!-- Header -->
        <!-- <div class="page-header">
            <div class="header-left">
                <div>
                    <h1 class="page-title">报表管理</h1>
                    <p class="page-description">查看、审核及管理企业上报的数据报表</p>
                </div>
            </div>
        </div> -->

        <!-- Nav Tabs (Card Style) -->
        <div class="nav-card">
            <div class="nav-tabs">
                <router-link
                    to="/home/dataManage/all"
                    class="nav-tab"
                    :class="{ active: activeTab === 'all' }"
                >
                    所有报表
                </router-link>
                <router-link
                    to="/home/dataManage/pending"
                    class="nav-tab"
                    :class="{ active: activeTab === 'pending' }"
                >
                    待审核报表
                </router-link>
                <router-link
                    to="/home/dataManage/pending-upload"
                    class="nav-tab"
                    :class="{ active: activeTab === 'pending-upload' }"
                >
                    待上传报表
                </router-link>
            </div>
        </div>

        <!-- Search Card -->
        <div class="search-card">
            <div class="search-section">
                <el-form :inline="true" :model="searchParams" class="query-form">
                    <el-form-item v-if="activeTab !== 'pending-upload'" label="企业名称">
                        <el-input
                            v-model="searchParams.enterpriseName"
                            placeholder="请输入企业名称"
                            class="custom-input"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item v-if="activeTab !== 'pending-upload'" label="所属行业">
                        <el-select
                            v-model="searchParams.industry"
                            placeholder="请选择行业"
                            clearable
                            class="custom-select"
                            style="width: 180px"
                        >
                            <el-option
                                v-for="industry in industryOptions"
                                :key="industry.code"
                                :label="industry.name"
                                :value="industry.code"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="activeTab !== 'pending-upload'" label="企业性质">
                        <el-select
                            v-model="searchParams.nature"
                            placeholder="请选择企业性质"
                            clearable
                            class="custom-select"
                            style="width: 180px"
                        >
                            <el-option
                                v-for="nature in natureOptions"
                                :key="nature.code"
                                :label="nature.name"
                                :value="nature.code"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="activeTab !== 'pending-upload'" label="地区">
                        <el-select
                            v-model="searchParams.region"
                            placeholder="请选择地区"
                            clearable
                            class="custom-select"
                            style="width: 180px"
                        >
                            <el-option
                                v-for="region in regionOptions"
                                :key="region.value"
                                :label="region.label"
                                :value="region.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="调查期">
                        <el-select
                            v-model="searchParams.investigatePeriod"
                            placeholder="选择调查期"
                            clearable
                            filterable
                            class="custom-select"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="p in periodOptions"
                                :key="p.value"
                                :label="p.label"
                                :value="p.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" class="btn-primary-theme" @click="handleSearch">
                            <el-icon class="mr-1"><search /></el-icon>搜索
                        </el-button>
                        <el-button @click="resetSearch" class="btn-secondary">重置</el-button>
                    </el-form-item>
                </el-form>

                <!-- Batch Actions -->
                <div v-if="activeTab === 'pending'" class="batch-actions">
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :disabled="selectedRows.length === 0"
                        @click="showBatchConfirmDialog = true"
                    >
                        批量审核通过
                    </el-button>
                    <el-button
                        type="danger"
                        class="btn-danger-theme"
                        :disabled="selectedRows.length === 0"
                        @click="showBatchRejectDialog = true"
                    >
                        批量驳回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- Table Card -->
        <div class="table-card">
            <div class="table-section" v-if="activeTab !== 'pending-upload'">
                <el-table
                    :data="reportList"
                    v-loading="loading"
                    style="width: 100%"
                    class="modern-table"
                    @selection-change="handleSelectionChange"
                    row-key="reportId"
                    :header-cell-style="{
                        background: '#f8fafc',
                        color: '#475569',
                        fontWeight: '700',
                        fontSize: '13px',
                        height: '56px',
                        textAlign: 'center',
                        borderBottom: '1px solid #f1f5f9',
                    }"
                    :cell-style="{ textAlign: 'center', padding: '8px 0' }"
                    :row-style="{ height: '72px' }"
                >
                    <el-table-column
                        v-if="activeTab === 'pending'"
                        type="selection"
                        width="55"
                        align="center"
                    />
                    <el-table-column
                        prop="enterpriseName"
                        label="企业名称"
                        min-width="180"
                        show-overflow-tooltip
                        align="left"
                    >
                        <template #default="{ row }">
                            <span class="cell-primary-text">{{ row.enterpriseName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="investigateTime"
                        label="调查期"
                        min-width="120"
                        align="center"
                    >
                        <template #default="{ row }">
                            <span class="cell-text">{{ row.investigateTime }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="industryName"
                        label="行业"
                        min-width="140"
                        align="center"
                    />
                    <el-table-column
                        prop="natureName"
                        label="企业性质"
                        min-width="120"
                        align="center"
                    />
                    <el-table-column
                        prop="regionName"
                        label="地区"
                        min-width="100"
                        align="center"
                    />
                    <el-table-column label="就业人数 (建档/调查)" min-width="160" align="center">
                        <template #default="{ row }">
                            <span class="cell-text"
                                >{{ row.constructionCount }} / {{ row.investigationCount }}</span
                            >
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="120" align="center">
                        <template #default="{ row }">
                            <div
                                class="status-badge"
                                :class="`status-${getStatusType(row.status)}`"
                            >
                                <span class="status-dot"></span>
                                {{ getStatusName(row.status) }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="220" align="center" fixed="right">
                        <template #default="scope">
                            <div class="action-group">
                                <el-button
                                    link
                                    type="primary"
                                    class="action-btn"
                                    @click="viewReportDetail(scope.row.reportId)"
                                >
                                    详情
                                </el-button>
                                <template v-if="scope.row.status === 1">
                                    <div class="divider"></div>
                                    <el-button
                                        link
                                        type="warning"
                                        class="action-btn warning"
                                        @click="remindReport(scope.row.reportId)"
                                    >
                                        提醒
                                    </el-button>
                                </template>
                                <template v-if="scope.row.status === 2">
                                    <div class="divider"></div>
                                    <el-button
                                        link
                                        type="primary"
                                        class="action-btn success"
                                        @click="approveReport(scope.row)"
                                    >
                                        通过
                                    </el-button>
                                    <div class="divider"></div>
                                    <el-button
                                        link
                                        type="danger"
                                        class="action-btn danger"
                                        @click="rejectReport(scope.row)"
                                    >
                                        驳回
                                    </el-button>
                                </template>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- Pagination -->
                <div class="pagination-wrapper">
                    <el-pagination
                        v-model:current-page="pagination.page"
                        v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>

            <div class="table-section" v-else>
                <div v-if="pendingUploadPeriods.length === 0" class="empty-tip">
                    <el-empty description="暂无已审核待上传的报表" />
                </div>
                <el-collapse v-model="activePeriodPanels" class="custom-collapse">
                    <el-collapse-item
                        v-for="period in pendingUploadPeriods"
                        :key="period.key"
                        :name="period.key"
                    >
                        <template #title>
                            <div class="period-header">
                                <div class="period-title">调查期：{{ period.label }}</div>
                                <div class="period-actions">
                                    <el-tag type="success" effect="dark" round
                                        >已审核：{{
                                            periodPaginationMap[period.key]?.total ?? 0
                                        }}</el-tag
                                    >
                                    <el-button
                                        size="small"
                                        type="success"
                                        class="btn-success-theme"
                                        :loading="uploadingPeriodMap[period.key] === true"
                                        @click.stop="uploadPeriod(period.key)"
                                        >上传本期全部</el-button
                                    >
                                </div>
                            </div>
                        </template>
                        <el-table
                            :data="periodDataMap[period.key]?.list || []"
                            row-key="reportId"
                            style="width: 100%"
                            class="modern-table sub-table"
                            :header-cell-style="{
                                background: '#f8fafc',
                                color: '#475569',
                                fontWeight: '700',
                            }"
                        >
                            <el-table-column
                                prop="enterpriseName"
                                label="企业名称"
                                min-width="160"
                            />
                            <el-table-column prop="industryName" label="行业" min-width="120" />
                            <el-table-column prop="natureName" label="企业性质" min-width="120" />
                            <el-table-column prop="regionName" label="地区" min-width="120" />
                            <el-table-column
                                prop="investigateTime"
                                label="调查期"
                                min-width="120"
                            />
                            <el-table-column label="操作" width="120" fixed="right" align="center">
                                <template #default="scope">
                                    <el-button
                                        link
                                        type="primary"
                                        class="action-btn"
                                        @click="viewReportDetail(scope.row.reportId)"
                                    >
                                        详情
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pagination-wrapper">
                            <el-pagination
                                :current-page="periodPaginationMap[period.key]?.page || 1"
                                :page-size="periodPaginationMap[period.key]?.pageSize || 5"
                                :page-sizes="[5]"
                                layout="total, prev, pager, next"
                                :total="periodPaginationMap[period.key]?.total || 0"
                                @current-change="(p) => handlePeriodPageChange(period.key, p)"
                            />
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </div>
        </div>

        <!-- Dialogs (Using shared custom styling) -->

        <!-- Approve Confirmation -->
        <el-dialog
            v-model="showApproveDialog"
            title="确认审核通过"
            width="400px"
            class="custom-dialog"
            align-center
        >
            <div class="dialog-body-text">确定要审核通过该报表吗？</div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showApproveDialog = false" class="btn-secondary"
                        >取消</el-button
                    >
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :loading="actionLoading"
                        @click="confirmApprove"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>

        <!-- Reject Dialog -->
        <el-dialog
            v-model="showRejectDialog"
            title="驳回报表"
            width="500px"
            class="custom-dialog"
            align-center
        >
            <el-form :model="rejectForm" label-position="top">
                <el-form-item label="驳回原因" required>
                    <el-input
                        v-model="rejectForm.rejectReason"
                        type="textarea"
                        rows="4"
                        placeholder="请输入驳回原因"
                        class="custom-input"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showRejectDialog = false" class="btn-secondary"
                        >取消</el-button
                    >
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :loading="actionLoading"
                        @click="confirmReject"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>

        <!-- Batch Confirm Dialog -->
        <el-dialog
            v-model="showBatchConfirmDialog"
            title="批量操作确认"
            width="400px"
            class="custom-dialog"
            align-center
        >
            <div class="dialog-body-text">
                确定要{{ activeTab === 'pending' ? '批量审核通过' : '批量上传' }}选中的
                <span class="highlight-count">{{ selectedRows.length }}</span> 条报表吗？
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showBatchConfirmDialog = false" class="btn-secondary"
                        >取消</el-button
                    >
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :loading="actionLoading"
                        @click="confirmBatchAction"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>

        <!-- Batch Reject Dialog -->
        <el-dialog
            v-model="showBatchRejectDialog"
            title="批量驳回"
            width="500px"
            class="custom-dialog"
            align-center
        >
            <el-form :model="batchRejectForm" label-position="top">
                <el-form-item label="驳回原因" required>
                    <el-input
                        v-model="batchRejectForm.rejectReason"
                        type="textarea"
                        rows="4"
                        placeholder="请输入驳回原因"
                        class="custom-input"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showBatchRejectDialog = false" class="btn-secondary"
                        >取消</el-button
                    >
                    <el-button
                        type="primary"
                        class="btn-primary-theme"
                        :loading="actionLoading"
                        @click="confirmBatchReject"
                        >确定</el-button
                    >
                </div>
            </template>
        </el-dialog>

        <!-- Report Detail Dialog -->
        <el-dialog
            v-model="showDetailDialog"
            width="800px"
            class="custom-dialog"
            align-center
            @close="closeDetailDialog"
        >
            <template #header>
                <div class="custom-dialog-header">
                    <span class="title">报表详情</span>
                </div>
            </template>

            <div v-if="loadingDetail" class="loading-center">
                <span class="loading-text">加载中...</span>
            </div>
            <div v-else-if="reportDetail" class="view-content">
                <div class="detail-header-info">
                    <h2 class="enterprise-name">{{ reportDetail.enterpriseName }}</h2>
                    <div class="tags-row">
                        <el-tag type="info" effect="dark" round
                            >调查期：{{ reportDetail.investigateTime }}</el-tag
                        >
                        <el-tag type="primary" effect="dark" round
                            >减少类型：{{
                                getReductionTypeName(reportDetail.reductionType)
                            }}</el-tag
                        >
                    </div>
                </div>

                <el-descriptions :column="2" border class="custom-desc">
                    <el-descriptions-item label="建档期就业人数">
                        <span class="view-primary-text">{{ reportDetail.constructionCount }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="调查期就业人数">
                        <span class="view-primary-text">{{ reportDetail.investigationCount }}</span>
                    </el-descriptions-item>

                    <el-descriptions-item label="原因说明 1" :span="2">{{
                        reportDetail.reason1Desc || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="原因说明 2" :span="2">{{
                        reportDetail.reason2Desc || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="原因说明 3" :span="2">{{
                        reportDetail.reason3Desc || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="其他原因" :span="2">{{
                        reportDetail.otherReason || '-'
                    }}</el-descriptions-item>
                </el-descriptions>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDetailDialog" class="btn-secondary">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import dataManageApi from '../../api/dataManage';
import regionData from '../../dict/yunnan_region_code.json';
import enterpriseTypeData from '../../dict/enterprise_type.json';
import enterpriseIndustryData from '../../dict/enterprise_industry.json';
import employmentReductionTypes from '../../dict/employment_reduction_types.json';
import { Search } from '@element-plus/icons-vue';

// 路由相关
const route = useRoute();
const router = useRouter();

// 当前激活的标签页
const activeTab = computed(() => {
    const path = route.path;
    if (path.includes('/pending-upload')) return 'pending-upload';
    if (path.includes('/pending')) return 'pending';
    return 'all';
});

// 数据加载状态
const loading = ref(false);
const loadingDetail = ref(false);
const actionLoading = ref(false);

// 搜索参数
const searchParams = reactive({
    enterpriseName: '',
    industry: '',
    nature: '',
    investigateYear: '',
    investigateMonth: '',
    investigatePeriod: '',
    region: '',
});

// 分页参数
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0,
});

const activePeriodPanels = ref([]);
const periodPaginationMap = reactive({});
const periodDataMap = reactive({});

// 报表列表数据
const reportList = ref([]);

// 选中的行
const selectedRows = ref([]);

// 报表详情
const reportDetail = ref(null);

// 对话框状态
const showDetailDialog = ref(false);
const showApproveDialog = ref(false);
const showRejectDialog = ref(false);
const showBatchConfirmDialog = ref(false);
const showBatchRejectDialog = ref(false);

const uploadingPeriodMap = reactive({});

// 当前操作的报表
const currentReport = ref(null);

// 驳回表单
const rejectForm = reactive({
    rejectReason: '',
});

// 批量驳回表单
const batchRejectForm = reactive({
    rejectReason: '',
});

// 地区选项（仅获取市级数据）
const regionOptions = computed(() => {
    return [
        { label: '临沧市', value: 1 },
        { label: '丽江市', value: 2 },
        { label: '保山市', value: 3 },
        { label: '大理白族自治州', value: 4 },
        { label: '德宏傣族景颇族自治州', value: 5 },
        { label: '怒江傈僳族自治州', value: 6 },
        { label: '文山壮族苗族自治州', value: 7 },
        { label: '昆明市', value: 8 },
        { label: '昭通市', value: 9 },
        { label: '普洱市', value: 10 },
        { label: '曲靖市', value: 11 },
        { label: '楚雄彝族自治州', value: 12 },
        { label: '玉溪市', value: 13 },
        { label: '红河哈尼族彝族自治州', value: 14 },
        { label: '西双版纳傣族自治州', value: 15 },
        { label: '迪庆藏族自治州', value: 16 },
    ];
});

// 企业性质选项
const natureOptions = computed(() => {
    return enterpriseTypeData.map((item) => ({ code: item.code, name: item.name }));
});

// 行业选项
const industryOptions = computed(() => {
    return enterpriseIndustryData.map((item) => ({ code: item.code, name: item.name }));
});

const periodOptions = ref([]);
const activePeriodFilter = ref('');

const loadPeriods = async () => {
    try {
        const resp = await dataManageApi.getAuditPeriods();
        const payload = resp?.data ?? resp;
        const list = payload?.data ?? payload?.list ?? payload;
        const arr = Array.isArray(list) ? list : [];
        periodOptions.value = arr.map((it) => {
            const label = it?.investigateTime ?? it?.label ?? it?.name ?? it?.period ?? it;
            const value =
                it?.investigateTime ?? it?.value ?? it?.period ?? it?.label ?? it?.name ?? it;
            return { label: String(label), value: String(value) };
        });
    } catch (e) {
        periodOptions.value = [];
    }
};

const pendingUploadPeriods = computed(() => {
    const arr = Array.isArray(periodOptions.value) ? periodOptions.value : [];
    const target = activePeriodFilter.value || '';
    const source = target ? arr.filter((p) => String(p.value) === String(target)) : arr;
    return source
        .map((p) => ({ key: p.value, label: p.label }))
        .filter((p) => (periodPaginationMap[p.key]?.total ?? 1) > 0);
});

const preloadApprovedCounts = async () => {
    const periods = Array.isArray(pendingUploadPeriods.value) ? pendingUploadPeriods.value : [];
    const tasks = periods.map((p) => {
        ensurePeriodState(p.key);
        return dataManageApi
            .getPendingReviews({
                page: 1,
                pageSize: 1,
                status: 3,
                investigateTime: p.key,
            })
            .then((resp) => {
                const total = resp?.data?.totalCount ?? 0;
                periodPaginationMap[p.key].total = total;
            })
            .catch(() => {
                periodPaginationMap[p.key].total = 0;
            });
    });
    await Promise.allSettled(tasks);
};

// 获取减少类型名称（根据ID映射）
const getReductionTypeName = (reductionTypeId) => {
    if (!reductionTypeId) return '-';
    const index = parseInt(reductionTypeId) - 1;
    if (index >= 0 && index < employmentReductionTypes.length) {
        return employmentReductionTypes[index].label;
    }
    return '-';
};

// 获取状态名称
const getStatusName = (status) => {
    const statusMap = {
        1: '待市级审核',
        2: '待省级审核',
        3: '审核通过',
        4: '已归档',
        5: '驳回',
    };
    return statusMap[status] || '未知状态';
};

// 获取状态类型（用于标签颜色）
const getStatusType = (status) => {
    const typeMap = {
        1: 'info',
        2: 'warning',
        3: 'success',
        4: 'primary',
        5: 'danger',
    };
    return typeMap[status] || 'info';
};

const findNameByCode = (options, code) => {
    if (!code || !options || !Array.isArray(options)) return '-';
    const stack = [...options];
    while (stack.length) {
        const item = stack.shift();
        if (!item) continue;
        if (item.code === code) return item.name || '-';
        if (item.children && Array.isArray(item.children)) stack.push(...item.children);
    }
    return '-';
};

const formatIndustryName = (name) => {
    if (!name || typeof name !== 'string') return '-';
    return name.replace(/^\s*\d+\.?\s*/, '');
};

// 加载报表列表
const loadReports = async () => {
    loading.value = true;
    try {
        // 根据当前标签页设置查询参数
        let params = {
            page: pagination.page,
            pageSize: pagination.pageSize,
        };

        if (activeTab.value === 'pending-upload') {
            // 待上传页面按调查期分组，列表数据由各面板独立加载
            params = { page: 1, pageSize: 1 }; // 占位，避免不必要的全局加载
        } else {
            params = {
                ...params,
                enterpriseName: searchParams.enterpriseName,
                industry: searchParams.industry,
                nature: searchParams.nature,
                region: searchParams.region,
                reduction_type: searchParams.reductionType,
                investigateTime: searchParams.investigatePeriod || '',
            };
            if (activeTab.value === 'pending') {
                params.status = 2;
            }
        }

        // 调用API获取报表列表
        const response = await dataManageApi.getPendingReviews(params);

        if (response.data && response.data.list) {
            reportList.value = response.data.list.map((item) => ({
                ...item,
                industryName: formatIndustryName(
                    findNameByCode(enterpriseIndustryData, item.enterpriseIndustry)
                ),
                natureName: findNameByCode(enterpriseTypeData, item.enterpriseNature),
                regionName: findNameByCode(regionData, item.enterpriseRegion),
            }));
            if (activeTab.value !== 'pending-upload') {
                pagination.total = response.data.totalCount || 0;
            }
        }
    } finally {
        loading.value = false;
    }
};

// 处理搜索
const handleSearch = () => {
    if (activeTab.value === 'pending-upload') {
        const key = searchParams.investigatePeriod || '';
        activePeriodFilter.value = key;
        if (key) {
            ensurePeriodState(key);
            periodPaginationMap[key].page = 1;
            activePeriodPanels.value = [key];
            loadPeriodPage(key);
        } else {
            activePeriodPanels.value = [];
        }
        return;
    } else {
        pagination.page = 1;
        loadReports();
    }
};

// 重置搜索
const resetSearch = () => {
    Object.keys(searchParams).forEach((key) => {
        searchParams[key] = '';
    });
    if (activeTab.value === 'pending-upload') {
        activePeriodFilter.value = '';
        activePeriodPanels.value = [];
        return;
    } else {
        pagination.page = 1;
        loadReports();
    }
};

// 分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size;
    pagination.page = 1;
    loadReports();
};

// 当前页码变化
const handleCurrentChange = (current) => {
    pagination.page = current;
    loadReports();
};

// 选择变化
const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
};

// 查看报表详情
const viewReportDetail = async (reportId) => {
    showDetailDialog.value = true;
    loadingDetail.value = true;
    try {
        const response = await dataManageApi.getReportDetail(reportId);
        const payload = response?.data ?? response;
        reportDetail.value = payload?.data ?? payload;
    } catch (error) {
        console.error('获取报表详情失败:', error);
        ElMessage.error('获取报表详情失败，请重试');
    } finally {
        loadingDetail.value = false;
    }
};

// 关闭详情对话框
const closeDetailDialog = () => {
    reportDetail.value = null;
    showDetailDialog.value = false;
};

// 审核通过报表
const approveReport = (report) => {
    currentReport.value = report;
    showApproveDialog.value = true;
};

// 确认审核通过
const confirmApprove = async () => {
    if (!currentReport.value) return;

    actionLoading.value = true;
    try {
        const params = {
            enterpriseId: currentReport.value.enterpriseId,
            periodId: currentReport.value.periodId,
            reportId: currentReport.value.reportId,
        };
        await dataManageApi.approveReport(params);
        ElMessage.success('审核通过成功');
        showApproveDialog.value = false;
        await loadReports();
        await loadPeriods();
        await preloadApprovedCounts();
        const key = currentReport.value.investigateTime || '';
        if (key) {
            ensurePeriodState(key);
            periodPaginationMap[key].page = 1;
            await loadPeriodPage(key);
            if (!activePeriodPanels.value.includes(key)) {
                activePeriodPanels.value = [...activePeriodPanels.value, key];
            }
        }
    } catch (error) {
        console.error('审核通过失败:', error);
        ElMessage.error('审核通过失败，请重试');
    } finally {
        actionLoading.value = false;
    }
};

// 驳回报表
const rejectReport = (report) => {
    currentReport.value = report;
    rejectForm.rejectReason = '';
    showRejectDialog.value = true;
};

// 确认驳回
const confirmReject = async () => {
    if (!currentReport.value || !rejectForm.rejectReason.trim()) {
        ElMessage.warning('请输入驳回原因');
        return;
    }

    actionLoading.value = true;
    try {
        const params = {
            enterpriseId: currentReport.value.enterpriseId,
            periodId: currentReport.value.periodId,
            reportId: currentReport.value.reportId,
            rejectReason: rejectForm.rejectReason.trim(),
        };

        await dataManageApi.rejectReport(params);
        ElMessage.success('驳回成功');
        showRejectDialog.value = false;
        loadReports();
    } catch (error) {
        console.error('驳回失败:', error);
        ElMessage.error('驳回失败，请重试');
    } finally {
        actionLoading.value = false;
    }
};

// 提醒报表
const remindReport = async (reportId) => {
    try {
        await ElMessageBox.confirm('确定要提醒该报表的提交者吗？', '提醒确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-primary-theme',
            cancelButtonClass: 'btn-secondary',
        });

        // 这里应该调用提醒的API，暂时模拟成功
        // await dataManageApi.remindReport(reportId);

        ElMessage.success('提醒成功');
    } catch (error) {
        // 用户取消确认不算错误
        if (error !== 'cancel') {
            console.error('提醒失败:', error);
            ElMessage.error('提醒失败，请重试');
        }
    }
};

// 上传报表
const uploadReport = async (reportId, enterpriseId, periodId) => {
    try {
        await ElMessageBox.confirm('确定要上传该报表吗？', '上传确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-primary-theme',
            cancelButtonClass: 'btn-secondary',
        });

        const params = {
            reportId: reportId,
            enterpriseId: enterpriseId,
            periodId: periodId,
        };
        await dataManageApi.uploadReport(params);

        ElMessage.success('上传成功');
        loadReports();
    } catch (error) {
        // 用户取消确认不算错误
        if (error !== 'cancel') {
            console.error('上传失败:', error);
            ElMessage.error('上传失败，请重试');
        }
    }
};

const fetchAllPeriodReports = async (period) => {
    const resp = await dataManageApi.getPendingReviews({
        page: 1,
        pageSize: 1000,
        status: 3,
        investigateTime: period || '',
    });
    const list = resp?.data?.list ?? [];
    return list;
};

const uploadPeriod = async (periodKey) => {
    if (!periodKey) {
        ElMessage.warning('请先选择调查期');
        return;
    }
    try {
        await ElMessageBox.confirm('确定要上传该调查期的所有已审核报表吗？', '上传确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-primary-theme',
            cancelButtonClass: 'btn-secondary',
        });
        uploadingPeriodMap[periodKey] = true;
        const all = await fetchAllPeriodReports(periodKey);
        if (!all || all.length === 0) {
            periodPaginationMap[periodKey] = { page: 1, pageSize: 5, total: 0 };
            periodDataMap[periodKey] = { list: [] };
            activePeriodPanels.value = (activePeriodPanels.value || []).filter(
                (k) => k !== periodKey
            );
            return;
        }
        const items = all.map((report) => ({
            reportId: report.reportId,
            enterpriseId: report.enterpriseId,
            periodId: report.periodId,
        }));
        await dataManageApi.uploadReport({ items, period: periodKey });
        ElMessage.success('该调查期全部上传成功');
        periodPaginationMap[periodKey].total = 0;
        periodDataMap[periodKey].list = [];
        activePeriodPanels.value = (activePeriodPanels.value || []).filter((k) => k !== periodKey);
        await preloadApprovedCounts();
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量上传失败:', error);
            ElMessage.error('批量上传失败，请重试');
        }
    } finally {
        uploadingPeriodMap[periodKey] = false;
    }
};

const ensurePeriodState = (key) => {
    if (!periodPaginationMap[key]) periodPaginationMap[key] = { page: 1, pageSize: 5, total: 0 };
    if (!periodDataMap[key]) periodDataMap[key] = { list: [] };
};

const loadPeriodPage = async (key) => {
    ensurePeriodState(key);
    const state = periodPaginationMap[key];
    const resp = await dataManageApi.getPendingReviews({
        page: state.page,
        pageSize: state.pageSize,
        status: 3,
        investigateTime: key,
    });
    const list = resp?.data?.list ?? [];
    periodDataMap[key].list = list.map((item) => ({
        ...item,
        industryName: formatIndustryName(
            findNameByCode(enterpriseIndustryData, item.enterpriseIndustry)
        ),
        natureName: findNameByCode(enterpriseTypeData, item.enterpriseNature),
        regionName: findNameByCode(regionData, item.enterpriseRegion),
    }));
    periodPaginationMap[key].total = resp?.data?.totalCount ?? 0;
};

const handlePeriodPageChange = (key, p) => {
    ensurePeriodState(key);
    periodPaginationMap[key].page = p;
    loadPeriodPage(key);
};

watch(activePeriodPanels, (names) => {
    if (Array.isArray(names)) {
        names.forEach((key) => {
            ensurePeriodState(key);
            if ((periodDataMap[key].list ?? []).length === 0) {
                loadPeriodPage(key);
            }
        });
    }
});

// 批量操作确认
const confirmBatchAction = async () => {
    actionLoading.value = true;
    try {
        // 根据当前标签页执行不同的批量操作
        if (activeTab.value === 'pending') {
            // 批量审核通过
            for (const report of selectedRows.value) {
                const params = {
                    enterpriseId: report.enterpriseId,
                    periodId: report.periodId,
                    reportId: report.reportId,
                };
                await dataManageApi.approveReport(params);
            }
            ElMessage.success('批量审核通过成功');
            const keys = Array.from(
                new Set(selectedRows.value.map((r) => r.investigateTime).filter((v) => !!v))
            );
        } else if (activeTab.value === 'pending-upload') {
            for (const report of selectedRows.value) {
                const params = {
                    reportId: report.reportId,
                    enterpriseId: report.enterpriseId,
                    periodId: report.periodId,
                };
                await dataManageApi.uploadReport(params);
            }
            ElMessage.success('批量上传成功');
        }

        showBatchConfirmDialog.value = false;
        selectedRows.value = [];
        await loadReports();
        await loadPeriods();
        await preloadApprovedCounts();
        if (typeof keys !== 'undefined') {
            for (const k of keys) {
                ensurePeriodState(k);
                periodPaginationMap[k].page = 1;
                await loadPeriodPage(k);
                if (!activePeriodPanels.value.includes(k)) {
                    activePeriodPanels.value = [...activePeriodPanels.value, k];
                }
            }
        }
    } catch (error) {
        console.error('批量操作失败:', error);
        ElMessage.error('批量操作失败，请重试');
    } finally {
        actionLoading.value = false;
    }
};

// 批量驳回确认
const confirmBatchReject = async () => {
    if (!batchRejectForm.rejectReason.trim()) {
        ElMessage.warning('请输入驳回原因');
        return;
    }

    actionLoading.value = true;
    try {
        for (const report of selectedRows.value) {
            const params = {
                enterpriseId: report.enterpriseId,
                periodId: report.periodId,
                reportId: report.reportId,
                rejectReason: batchRejectForm.rejectReason.trim(),
            };
            await dataManageApi.rejectReport(params);
        }

        ElMessage.success('批量驳回成功');
        showBatchRejectDialog.value = false;
        selectedRows.value = [];
        loadReports();
    } catch (error) {
        console.error('批量驳回失败:', error);
        ElMessage.error('批量驳回失败，请重试');
    } finally {
        actionLoading.value = false;
    }
};

// 监听路由变化，重新加载数据
watch(activeTab, () => {
    selectedRows.value = [];
    pagination.page = 1;
    loadReports();
});

// 组件挂载时加载数据
onMounted(() => {
    loadReports();
    loadPeriods().then(() => preloadApprovedCounts());
});
</script>

<style scoped lang="scss">
/* --- Global Resets & Layout --- */
.page-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    padding: 24px 40px;
    box-sizing: border-box;
    // background-color: #f8fafc;
    color: #1e293b;
    font-family:
        'Inter',
        -apple-system,
        BlinkMacSystemFont,
        'Segoe UI',
        Roboto,
        sans-serif;
}

/* Header */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 40px;
    background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
    border-radius: 24px;
    color: white;
    box-shadow: 0 20px 40px -12px rgba(79, 70, 229, 0.3);
}

.header-left {
    display: flex;
    align-items: center;
    gap: 24px;
}

.page-title {
    font-size: 28px;
    font-weight: 800;
    margin: 0 0 8px 0;
    letter-spacing: -0.02em;
    color: white;
}

.page-description {
    font-size: 15px;
    opacity: 0.9;
    margin: 0;
    font-weight: 400;
    color: white;
}

/* Nav Tabs */
.nav-card {
    background: white;
    border-radius: 16px;
    padding: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
    border: 1px solid #f1f5f9;
    display: flex;
    justify-content: flex-start; /* Changed from center to flex-start */
}

.nav-tabs {
    display: flex;
    gap: 8px;
    background: #f1f5f9;
    padding: 4px;
    border-radius: 12px;
}

.nav-tab {
    padding: 8px 24px;
    font-size: 14px;
    font-weight: 600;
    color: #64748b;
    text-decoration: none;
    border-radius: 8px;
    transition: all 0.2s;

    &.active {
        background: white;
        color: #4f46e5;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }

    &:hover:not(.active) {
        color: #475569;
        background: rgba(255, 255, 255, 0.5);
    }
}

/* Search Card */
.search-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    padding: 24px;
    margin-bottom: 24px;
    border: 1px solid rgba(241, 245, 249, 1);
}

.query-form {
    margin-bottom: 0;
    :deep(.el-form-item) {
        margin-bottom: 0;
        margin-right: 24px;
    }
    :deep(.el-form-item:last-child) {
        margin-right: 0;
    }
}

.search-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
}

/* Table Card */
.table-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
    padding: 8px;
}

/* Modern Table Styles */
.modern-table {
    border-radius: 16px;
    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
}

.cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
}

.cell-text {
    font-size: 13px;
    color: #64748b;
}

.timestamp-text {
    font-variant-numeric: tabular-nums;
    color: #334155;
    font-size: 13px;
    font-weight: 500;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    border-radius: 99px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.5;
}

.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
}

.status-success {
    background: #ecfdf5;
    color: #059669;
    .status-dot {
        background: #10b981;
    }
}
.status-primary {
    background: #eff6ff;
    color: #2563eb;
    .status-dot {
        background: #3b82f6;
    }
}
.status-warning {
    background: #fff7ed;
    color: #ea580c;
    .status-dot {
        background: #f97316;
    }
}
.status-danger {
    background: #fef2f2;
    color: #dc2626;
    .status-dot {
        background: #ef4444;
    }
}
.status-info {
    background: #f1f5f9;
    color: #64748b;
    .status-dot {
        background: #94a3b8;
    }
}

/* Buttons */
.btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
    transition: all 0.2s ease;
    padding: 8px 20px;
}

.btn-primary-theme:hover {
    background: linear-gradient(135deg, #4338ca 0%, #4f46e5 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(79, 70, 229, 0.35);
}

.btn-danger-theme {
    background: #ef4444 !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    padding: 8px 20px;
    transition: all 0.2s ease;

    &:hover {
        background: #dc2626 !important;
    }
}

.btn-success-theme {
    background: #10b981 !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;

    &:hover {
        background: #059669 !important;
    }
}

.btn-secondary {
    background: #fff;
    border: 1px solid #e2e8f0;
    color: #475569;
    font-weight: 500;
    border-radius: 8px;
    padding: 8px 20px;
}

.btn-secondary:hover {
    background: #f8fafc;
    color: #1e293b;
    border-color: #cbd5e1;
}

.action-group {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.divider {
    width: 1px;
    height: 14px;
    background: #e2e8f0;
}

.action-btn {
    font-weight: 600;
    padding: 4px 8px;
    height: auto;

    &.warning {
        color: #ea580c;
        &:hover {
            color: #c2410c;
        }
    }
    &.success {
        color: #16a34a;
        &:hover {
            color: #15803d;
        }
    }
    &.danger {
        color: #ef4444;
        &:hover {
            color: #dc2626;
        }
    }
}

.pagination-wrapper {
    padding: 16px 24px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #f1f5f9;
}

/* Inputs */
.custom-input,
.custom-select {
    :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        padding: 6px 12px;
        &.is-focus {
            box-shadow: 0 0 0 2px #818cf8 inset;
        }
    }
}

/* Dialog Customization */
:deep(.custom-dialog) {
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);

    .el-dialog__header {
        margin: 0;
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        .el-dialog__title {
            font-weight: 700;
            font-size: 18px;
            color: #0f172a;
        }
    }

    .el-dialog__body {
        padding: 32px;
    }

    .el-dialog__footer {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background-color: #f8fafc;
    }
}

.dialog-body-text {
    font-size: 16px;
    color: #334155;
    text-align: center;
    padding: 20px 0;
}

.highlight-count {
    color: #4f46e5;
    font-weight: 700;
    font-size: 18px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* Report Detail */
.detail-header-info {
    margin-bottom: 24px;
}

.enterprise-name {
    font-size: 20px;
    font-weight: 700;
    color: #1e293b;
    margin: 0 0 8px 0;
}

.tags-row {
    display: flex;
    gap: 8px;
}

.view-primary-text {
    font-size: 15px;
    font-weight: 600;
    color: #0f172a;
}

/* Collapse Customization */
.custom-collapse {
    border: none;
    :deep(.el-collapse-item__header) {
        font-size: 15px;
        font-weight: 600;
        color: #1e293b;
        background-color: white;
        padding: 16px 24px;
        border-bottom: 1px solid #f1f5f9;
        &.is-active {
            border-bottom-color: transparent;
        }
    }
    :deep(.el-collapse-item__wrap) {
        border-bottom: none;
    }
    :deep(.el-collapse-item__content) {
        padding: 0;
    }
}

.period-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding-right: 12px;
}

.period-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.sub-table {
    border-radius: 0;
    :deep(.el-table__inner-wrapper::before) {
        display: none;
    }
}

.empty-tip {
    padding: 40px;
    text-align: center;
}

.loading-center {
    display: flex;
    justify-content: center;
    padding: 50px;
    color: #94a3b8;
}

.mr-1 {
    margin-right: 4px;
}
</style>

<style lang="scss">
/* Global styles for ElMessageBox */
.custom-message-box {
    border-radius: 16px !important;
    overflow: hidden;
    border: none !important;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
    padding-bottom: 20px !important;

    .el-message-box__header {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;

        .el-message-box__title {
            font-weight: 700;
            color: #0f172a;
        }
    }

    .el-message-box__content {
        padding: 24px;
        color: #334155;
        font-size: 15px;
    }

    .el-message-box__btns {
        padding: 0 24px 0 0;

        .el-button {
            border-radius: 8px;
            font-weight: 600;
            padding: 10px 20px;
            height: auto;
        }

        .btn-primary-theme {
            background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
            border: none;
            color: white;

            &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
            }
        }

        .btn-secondary {
            background: #fff;
            border: 1px solid #e2e8f0;
            color: #475569;

            &:hover {
                background: #f8fafc;
                color: #1e293b;
            }
        }
    }
}

/* Global styles for Element Plus Poppers (Dropdowns, Tooltips, etc.) */
.el-popper.is-light {
    border-radius: 12px !important;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.15) !important;
    border: 1px solid #f1f5f9 !important;
}

.el-select-dropdown {
    border-radius: 12px !important;
    overflow: hidden;
}

.el-select__popper {
    border-radius: 12px !important;
}
</style>
